package com.sudoku.listener;

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.sudoku.common.Constants;
import com.sudoku.common.SqliteUtils;
import com.sudoku.ui.Sudoku;
import com.sudoku.ui.content.SMenu;
import com.sudoku.ui.content.SPanel;

public class MenuReadHistoryListener implements ActionListener {
	private int id;
	private Sudoku sudoku;
	
	public MenuReadHistoryListener(Sudoku sudoku, int id) {
		this.sudoku = sudoku;
		this.id = id;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		/**
		 * 如果当前正在进行游戏，则需要将当前进度存档
		 */
		if (Constants.LABEL_PUZZLE.equals(sudoku.getAtCard())) {
			SqliteUtils.insert(sudoku);
		}
		/**
		 * 从数据库中读取记录
		 * 1. tfCells 玩家的填写情况
		 * 2. puzzle 答案
		 * 3. mask 题面遮盖情况
		 * 4. level 此题的难度
		 */
		
		String[][] jTextFields = SqliteUtils.selectTfCellsById(id);
		int[][] puzzle = SqliteUtils.selectPuzzleById(id);
		boolean[][] mask = SqliteUtils.selectMaskById(id);
		int level = SqliteUtils.selectLevelById(id);
		SPanel sPanel = new SPanel(sudoku, level, jTextFields, puzzle, mask);
		sudoku.setPanel(sPanel);
		sudoku.getCards().add(sPanel, Constants.LABEL_PUZZLE);
	
		SqliteUtils.delete(id); // 根据id删除数据库中被读取的记录
		CardLayout cardLayout = (CardLayout)(sudoku.getCards().getLayout());
		cardLayout.show(sudoku.getCards(), Constants.LABEL_PUZZLE); // 跳转页面
		sudoku.setAtCard(Constants.LABEL_PUZZLE);
		sudoku.setLevel(level);
		sudoku.setMenu(new SMenu(sudoku)); // 更新菜单
	}
}
